using LiJ.Framework.Msg.Mos;
using System;

namespace LiJ.Framework.Msg
{
	/// <summary>
	///  自定义消息处理Handler基类
	/// 【用户自定义请返回：WxMsgCustomMsgHandler&lt;TRecMsg&gt;或其子类】
	/// </summary>
	public abstract class WxMsgProcessor
	{
		internal bool CanExecute
		{
			get;
			set;
		}

		protected internal abstract WxBaseReplyMsg Execute(WxBaseRecMsg msg);

		protected internal abstract WxBaseRecMsg CreateNewInstance();
	}
	/// <inheritdoc />
	/// <summary>
	///   内部自定义消息类型处理Processor
	/// </summary>
	/// <typeparam name="TRecMsg"></typeparam>
	public class WxMsgProcessor<TRecMsg> : WxMsgProcessor where TRecMsg : WxBaseRecMsg, new()
	{
		private Func<TRecMsg, WxBaseReplyMsg> _processFunc;

		/// <summary>
		/// 处理方法实现
		/// </summary>
		public Func<TRecMsg, WxBaseReplyMsg> ProcessFunc
		{
			get
			{
				return this._processFunc;
			}
			set
			{
				base.CanExecute = true;
				this._processFunc = value;
			}
		}

		/// <summary>
		///  对应的接受消息创建实例方法
		///    如果不设置，会通过反射创建
		/// </summary>
		public Func<TRecMsg> RecInsCreater
		{
			get;
			set;
		}

		protected internal override WxBaseReplyMsg Execute(WxBaseRecMsg msg)
		{
			Func<TRecMsg, WxBaseReplyMsg> processFunc = this.ProcessFunc;
			if (processFunc == null)
			{
				return null;
			}
			return processFunc((TRecMsg)(msg as TRecMsg));
		}

		protected internal override WxBaseRecMsg CreateNewInstance()
		{
			Func<TRecMsg> recInsCreater = this.RecInsCreater;
			return (WxBaseRecMsg)(object)(((recInsCreater != null) ? recInsCreater() : null) ?? new TRecMsg());
		}
	}
}
